package com.orchard.orchardfarmmanagementsystem.controller;


import com.orchard.orchardfarmmanagementsystem.dto.MaintenanceRecordsDTO;
import com.orchard.orchardfarmmanagementsystem.dto.MaterialDTO;
import com.orchard.orchardfarmmanagementsystem.dto.SuppliesDTO;
import com.orchard.orchardfarmmanagementsystem.service.SuppliesService;
import com.orchard.orchardfarmmanagementsystem.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api")
public class SuppliesController {

    @Autowired
    private SuppliesService suppliesService;

    @GetMapping("/supplies")
    @PreAuthorize("hasAuthority('PERM_READ_DATA')")
    public Result<List<MaterialDTO>> getMaterialsinfo(){
        try{
            List<MaterialDTO> orchardInfo = suppliesService.getAllMaterials();
            return Result.success("获取果园信息成功",orchardInfo);
        }catch (Exception e){
            return Result.error(50001,"获取果园信息失败");

        }
    }



    // 创建物资
    @PostMapping("/supplies")
    @PreAuthorize("hasAuthority('PERM_ADMIN_DASHBOARD')")
    public Result<SuppliesDTO> createMaterial(@RequestBody SuppliesDTO supplyData) {
        try {
            SuppliesDTO createdSupply = suppliesService.createMaterial(supplyData);
            return Result.success("创建物资成功", createdSupply);
        } catch (Exception e) {
            e.printStackTrace();  // 或者记录日志
            return Result.error(50001, "创建物资失败");
        }
    }

    // 更新物资
    @PutMapping("/supplies/{id}")
    @PreAuthorize("hasAuthority('PERM_ADMIN_DASHBOARD')")
    public Result<SuppliesDTO> updateMaterial(@PathVariable Integer id, @RequestBody SuppliesDTO supplyData) {
        try {
            SuppliesDTO updatedSupply = suppliesService.updateMaterial(id, supplyData);
            return Result.success("更新物资成功", updatedSupply);
        } catch (Exception e) {
            e.printStackTrace();  // 或者记录日志
            return Result.error(50001, "更新物资失败");
        }
    }

    // 删除物资
    @DeleteMapping("/supplies/{id}")
    @PreAuthorize("hasAuthority('PERM_ADMIN_DASHBOARD')")
    public Result deleteMaterial(@PathVariable Integer id) {
        try {
            return suppliesService.deleteMaterial(id);

        } catch (Exception e) {
            e.printStackTrace();  // 或者记录日志
            return Result.error(50001, "删除物资失败");
        }
    }
}
